package com.sdkj.fixed.asset.assets.service;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.WarehousePagesParam;
import com.sdkj.fixed.asset.api.assets.in_vo.WarehouseParam;
import com.sdkj.fixed.asset.api.assets.out_vo.UserInfo;
import com.sdkj.fixed.asset.api.assets.out_vo.WarehouseResult;
import com.sdkj.fixed.asset.api.login.out_vo.CompanyBaseListResult;
import com.sdkj.fixed.asset.api.login.pojo.LoginRole;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.*;
import com.sdkj.fixed.asset.common.base.BaseMapper;
import com.sdkj.fixed.asset.common.base.BaseService;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.ObjectUtil;
import com.sdkj.fixed.asset.pojo.assets.*;
import com.sdkj.fixed.asset.pojo.system.OrgManagement;
import com.sdkj.fixed.asset.pojo.system.UsageManagement;
import com.sdkj.fixed.asset.pojo.system.UserManagement;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author zhangjinfei
 * @Description //TODO 资产入库
 * @Date 2020/7/21 10:54
 */
@Service
public class WarehouseService extends BaseService<Warehouse> {

    private Logger log = LoggerFactory.getLogger(WarehouseService.class);
    @Resource
    private WarehouseMapper mapper;
    @Resource
    private AssetLogMapper assetLogMapper;
    @Resource
    private AssetSupplierMapper assetSupplierMapper;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SetClassMapper setClassMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AssetReportService assetReportService;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private WarehouseImportDataVerifyHandler warehouseImportDataVerifyHandler;
    @Autowired
    private ScrapMapper scrapMapper;
    @Autowired
    private AssetReportMapper assetReportMapper;

    @Override
    public BaseMapper getMapper() {
        return mapper;
    }

    /**
     * 分页查询资产
     *
     * @param params
     * @return
     */
    public List<WarehouseResult> queryPages(PageParams<WarehousePagesParam> params) {
        WarehousePagesParam param = params.getParams();
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        Boolean flag = true;
        // redis 查询用户权限： 如果是管理员为false 查询全部
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if (isAllData == 1) {
            flag = false;
        }
        if (flag) {
            // 查询公司
            String companyType = "1";
            List<String> companyList = mapper.queryRelationIdLists(userId, companyType);
            //资产类别
            String classType = "2";
            List<String> classList = mapper.queryRelationIdLists(userId, classType);
            // 查询区域
            String areaType = "3";
            List<String> areaList = mapper.queryRelationIdLists(userId, areaType);
            if ((companyList == null || companyList.size() == 0) || (classList == null || classList.size() == 0) || (areaList == null || areaList.size() == 0)) {
                return new ArrayList<WarehouseResult>();
            }
            param.setCompanyList(companyList);
            param.setClassList(classList);
            param.setAreaList(areaList);
        }
        param.setOrgId(orgId);
        param.setAdminId(userId);
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<WarehouseResult> warehouseList = mapper.queryPages(param);
        warehouseList.stream().forEach(e -> {
            List<AssetLog> assetLogs = assetLogMapper.queryLogByAssetId(e.getAssetId());
            e.setLogList(assetLogs);

            // 修改分类名
//            setClassName(e);
        });
        return warehouseList;
    }

//    private void setClassName(WarehouseResult e) {
//        String classTreecode = e.getClassTreecode();
//        String[] split = classTreecode.split(",");
//        List<String> list = Arrays.asList(split);
//        String className = mapper.queryClassName(list);
//        e.setAssetClassName(className);
//    }

    public List<WarehouseResult> queryStatePages(PageParams<WarehousePagesParam> params) {
        List<WarehouseResult> warehouseResults = queryPages(params);
        warehouseResults.stream().forEach(e -> {
            List<AssetLog> assetLogs = assetLogMapper.queryLogByAssetId(e.getAssetId());
            e.setLogList(assetLogs);
            // 修改分类名
//            setClassName(e);
        });
        return warehouseResults;
    }

    public List<WarehouseResult> queryWithdrawal(WarehousePagesParam param) {
        param.setAdminId(request.getHeader("userId"));
        // 查询退库资产
        List<WarehouseResult> warehouseResults = mapper.queryPages(param);
        warehouseResults.stream().forEach(e -> {
            List<AssetLog> assetLogs = assetLogMapper.queryLogByAssetId(e.getAssetId());
            e.setLogList(assetLogs);
            // 修改分类名
//            setClassName(e);
        });
        return warehouseResults;
    }

    public List<WarehouseResult> queryAll(String token, String companyDeptId, String searchName) {
        WarehousePagesParam param = new WarehousePagesParam();
        param.setSearchName(searchName);
        param.setCompanyDeptId(companyDeptId);
        Boolean flag = true;
        // redis 查询用户权限： 如果是管理员为false 查询全部
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        List<CompanyBaseListResult> companys = loginUser.getCompanys();
        String orgId = companys.get(0).getCompanyId();
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if (isAllData == 1) {
            flag = false;
        }
        // redis 查询用户权限： 如果是管理员为false 查询全部
        if (flag) {
            // 查询公司
            String companyType = "1";
            List<String> companyList = mapper.queryRelationIdLists(userId, companyType);
            //资产类别
            String classType = "2";
            List<String> classList = mapper.queryRelationIdLists(userId, classType);
            // 查询区域
            String areaType = "3";
            List<String> areaList = mapper.queryRelationIdLists(userId, areaType);

            param.setCompanyList(companyList);
            param.setClassList(classList);
            param.setAreaList(areaList);
        }
        param.setOrgId(orgId);
        param.setAdminId(request.getHeader("userId"));
        List<WarehouseResult> warehouseList = mapper.queryPages(param);
        warehouseList.stream().forEach(e -> {
            List<AssetLog> assetLogs = assetLogMapper.queryLogByAssetId(e.getAssetId());
            if (assetLogs == null || assetLogs.size() == 0) {
                assetLogs = new ArrayList<>();
                assetLogs.add(new AssetLog());
            }
            e.setLogList(assetLogs);
            // 修改分类名
//            setClassName(e);
        });
        return warehouseList;
    }

    public WarehouseResult queryByAssetId(String assetId) {
        WarehouseResult warehouse = mapper.queryByAssetId(assetId);
        return warehouse;
    }

    public Integer queryCountByUserId(String userId) {
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        List<CompanyBaseListResult> companys = loginUser.getCompanys();
        String orgId = companys.get(0).getCompanyId();
        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("handlerUserId", userId);
        criteria.andEqualTo("orgId", orgId);
        criteria.andNotEqualTo("state", "待发放");
        Integer i = mapper.selectCountByExample(example);
        return i;
    }

    public List<WarehouseResult> queryByUserId(String userId, String searchName) {
//        通过用户ID 进行查询所有资产
        WarehousePagesParam param = new WarehousePagesParam();
        param.setUserId(userId);
        param.setSearchName(searchName);
        param.setState("10");
        List<WarehouseResult> warehouseList = mapper.queryPages(param);
        warehouseList.stream().forEach(e -> {
            List<AssetLog> assetLogs = assetLogMapper.queryLogByAssetId(e.getAssetId());
            if (assetLogs == null || assetLogs.size() == 0) {
                assetLogs = new ArrayList<>();
                assetLogs.add(new AssetLog());
            }
            e.setLogList(assetLogs);
        });
        return warehouseList;
    }


    public List<WarehouseResult> queryByClassId(String classId, String searchName) {
//        通过分类进行查看，该分类下有哪些资产
        String orgId = request.getHeader("orgId");
        WarehousePagesParam param = new WarehousePagesParam();
        param.setTreeCode(classId);
        param.setSearchName(searchName);
        param.setState("0");
        param.setOrgId(orgId);
        List<WarehouseResult> warehouseList = mapper.queryPages(param);
        warehouseList.stream().forEach(e -> {
            List<AssetLog> assetLogs = assetLogMapper.queryLogByAssetId(e.getAssetId());
            if (assetLogs == null || assetLogs.size() == 0) {
                assetLogs = new ArrayList<>();
                assetLogs.add(new AssetLog());
            }
            e.setLogList(assetLogs);
        });
        return warehouseList;
    }

    /**
     * 资产入库添加
     *
     * @param warehouseParam
     * @return
     */
    public Integer insertWarehouse(WarehouseParam warehouseParam) {
        String token = request.getHeader("token");
        warehouseTotalNum(cacheUtils.getUserCompanyId(token));

        String assetClassId = warehouseParam.getAssetClassId();
        Example example = new Example(SetClass.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("pid", assetClassId);
        List<SetClass> list = setClassMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            throw new LogicException("只能选择子分类...");
        }
        insetBefore(warehouseParam);
        Integer i = mapper.insertSelective(warehouseParam);
        insertSupplier(warehouseParam);
        if (null != warehouseParam.getHandlerUserId() && !"".equals(warehouseParam.getHandlerUserId())) {
            AssetReport assetReport = new AssetReport();
            assetReport.setAssetId(warehouseParam.getAssetId());
            assetReport.setAmount(warehouseParam.getAmount());
            assetReport.setArYear(DateTools.currentYear());
            assetReport.setArMonth(DateTools.currentMonth());
            assetReport.setArDay(DateTools.currentDay());
            assetReport.setUseType(0);
            assetReport.setUseUserId(warehouseParam.getHandlerUserId());
            assetReportService.insertReport(assetReport);
        }
        return i;
    }

    /**
     * 添加维保信息
     *
     * @param warehouseParam
     */
    private void insertSupplier(WarehouseParam warehouseParam) {
        AssetSupplier supplier = new AssetSupplier();
        String assetId = warehouseParam.getAssetId();
        String supplierId = warehouseParam.getSupplierId();
        String supplierName = warehouseParam.getSupplierName();
        String supplierUserId = warehouseParam.getSupplierUserId();
        String supplierUser = warehouseParam.getSupplierUser();
        String expireTime = warehouseParam.getExpireTime();
        String explainText = warehouseParam.getExplainText();
        supplier.setAssetId(assetId);
        supplier.setSupplierId(supplierId);
        supplier.setSupplierName(supplierName);
        supplier.setSupplierUserId(supplierUserId);
        supplier.setSupplierUser(supplierUser);
        supplier.setExpireTime(expireTime);
        supplier.setExplainText(explainText);

        Integer j = assetSupplierMapper.insertSelective(supplier);
    }

    /**
     * 添加之前修改参数
     *
     * @param warehouse
     */
    private void insetBefore(WarehouseParam warehouse) {
        String token = request.getHeader("token");
        // redis 查询用户权限： 如果是管理员为false 查询全部
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String orgId = cacheUtils.getUserCompanyId(token);
        String companyNo = warehouse.getCompanyNo();
        String classNo = warehouse.getAssetClassNo();
        String areaNo = warehouse.getAreaNo();
        String strDate = DateTools.nowDayStr();
        Long increment = redisUtil.getIncr("ZCRK_" + companyNo + classNo + areaNo + strDate, DateTools.expiresTime());
        String no = String.format("%04d", Long.valueOf(increment));
//        公司编码（4）-资产分类（4）-区域（4位）-生成年月日（8位）示例：20200714-流水号4位
        warehouse.setAssetCode(companyNo + classNo + areaNo + strDate + no);
        // 使用人不为空就是在用
        if (null != warehouse.getHandlerUserId() && !"".equals(warehouse.getHandlerUserId())) {
            warehouse.setState("在用");
            // 通过使用人设置使用公司和使用部门===
            setCompanyAndDept(warehouse);

        } else {
            warehouse.setState("闲置");
        }
        warehouse.setOrgId(orgId);
        warehouse.setCreateTime(DateTools.nowDate());
        warehouse.setCreateUser(userId);
        warehouse.setUpdateTime(DateTools.nowDate());
        warehouse.setUpdateUser(userId);
        warehouse.setIsDelete(0);
    }

    // 通过使用人设置使用公司和使用部门===
    private void setCompanyAndDept(Warehouse warehouse) {
        if (StringUtils.isNotEmpty(warehouse.getHandlerUserId())) {
            UserManagement user = mapper.queryUserByUserId(warehouse.getHandlerUserId());
            OrgManagement org = mapper.queryOrgById(user.getCompanyId());
            OrgManagement dept = mapper.queryOrgById(user.getDeptId());
            warehouse.setUseCompany(org.getId());
            warehouse.setUseCompanyTreecode(org.getTreecode());
            warehouse.setUseDepartment(dept.getId());
            warehouse.setUseDeptTreecode(dept.getTreecode());
        }

    }

    /**
     * 修改之前修改参数
     *
     * @param warehouse
     */
    private void updateBefore(WarehouseParam warehouse) {
        String token = request.getHeader("token");
        // redis 查询用户权限： 如果是管理员为false 查询全部
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        warehouse.setUpdateTime(DateTools.nowDate());
        warehouse.setUpdateUser(userId);
    }

    /**
     * 资产入库修改
     *
     * @param warehouse
     * @return
     */
    public Integer updateWarehouse(WarehouseParam warehouse) {

        Warehouse wh = mapper.selectByPrimaryKey(warehouse.getAssetId());
        String handlerUserId = wh.getHandlerUserId();

        updateBefore(warehouse);
        if (null != warehouse.getHandlerUserId() && !"".equals(warehouse.getHandlerUserId())) {
            warehouse.setState("在用");
            setCompanyAndDept(warehouse);
        } else {
            warehouse.setState("闲置");
        }

        if (StringUtils.isEmpty(warehouse.getHandlerUserId())) {
            warehouse.setHandlerUser("");
            warehouse.setHandlerUserId("");
        }

        if (StringUtils.isEmpty(warehouse.getUseDeptTreecode())) {
            warehouse.setUseDepartment("");
            warehouse.setUseDeptTreecode("");
        }
        Integer i = mapper.updateByPrimaryKeySelective(warehouse);
        updateSupplier(warehouse);

        // 如果删除，去除盘点
        if (warehouse.getIsDelete() == 1) {
            String userId = request.getHeader("userId");
            String orgId = request.getHeader("orgId");
            scrapMapper.delInv(userId, orgId, Arrays.asList(warehouse.getAssetId()));
        }
        Boolean flag = true;
        if (handlerUserId == null) {
            if (warehouse.getHandlerUserId() == null) {
                // 相同
                flag = false;
            }
        } else {
            if (StringUtils.equals(handlerUserId, warehouse.getHandlerUserId())) {
                // 相同
                flag = false;
            }
        }
        if (flag && warehouse.getIsDelete() != 1 && null != warehouse.getHandlerUserId() && !"".equals(warehouse.getHandlerUserId())) {
            AssetReport assetReport = new AssetReport();
            assetReport.setAssetId(warehouse.getAssetId());
            assetReport.setAmount(warehouse.getAmount());
            assetReport.setArYear(DateTools.currentYear());
            assetReport.setArMonth(DateTools.currentMonth());
            assetReport.setArDay(DateTools.currentDay());
            assetReport.setUseType(0);
            assetReport.setUseUserId(warehouse.getHandlerUserId());
            assetReportService.insertReport(assetReport);
        }
        return i;
    }

    /**
     * 修改维保信息
     *
     * @param warehouseParam
     */
    private void updateSupplier(WarehouseParam warehouseParam) {
        String assetId = warehouseParam.getAssetId();
        // 通过 资产ID 查询
        Example example = new Example(AssetSupplier.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("assetId", assetId);
        AssetSupplier supplier = assetSupplierMapper.selectOneByExample(example);
        if (null != warehouseParam.getHandlerUserId() && !"".equals(warehouseParam.getHandlerUserId())) {
            warehouseParam.setState("在用");
        } else {
            warehouseParam.setState("闲置");
        }
        String supplierId = warehouseParam.getSupplierId();
        String supplierName = warehouseParam.getSupplierName();
        String supplierUserId = warehouseParam.getSupplierUserId();
        String supplierUser = warehouseParam.getSupplierUser();
        String expireTime = warehouseParam.getExpireTime();
        String explainText = warehouseParam.getExplainText();
        supplier.setAssetId(assetId);
        supplier.setSupplierId(supplierId);
        supplier.setSupplierName(supplierName);
        supplier.setSupplierUserId(supplierUserId);
        supplier.setSupplierUser(supplierUser);
        supplier.setExpireTime(expireTime);
        supplier.setExplainText(explainText);
        Integer j = assetSupplierMapper.updateByPrimaryKey(supplier);
    }

    public Workbook importTemplate(File file) throws IOException {
        Workbook wb = null;
        InputStream inputStream = new FileInputStream(file);
        POIFSFileSystem fs = new POIFSFileSystem(inputStream);
        wb = new HSSFWorkbook(fs);
        return wb;
    }

    public Boolean importAssetData(MultipartFile file) throws Exception {
//        String orgId = cacheUtils.getUserCompanyId(request.getHeader("token"));
//        String userId = cacheUtils.getUserId(request.getHeader("token"));
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(0);
        importParams.setHeadRows(1);
        // 需要验证
        importParams.setNeedVerfiy(true);
        importParams.setVerifyHandler(warehouseImportDataVerifyHandler);
        ExcelImportResult<WarehouseImportData> result = null;
        try {
            result = ExcelImportUtil.importExcelMore(file.getInputStream(), WarehouseImportData.class,
                    importParams);
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("资产批量导入上传文件数据失败"+e);
            throw new LogicException("上传文件数据失败，核对导入模板。");
        }

        log.info("是否校验失败: " + result.isVerfiyFail());
        log.info("校验失败的集合:" + JSONObject.toJSONString(result.getFailList()));
        log.info("校验通过的集合:" + JSONObject.toJSONString(result.getList()));
        //校验是否有错误
        List<WarehouseImportData> failList = result.getFailList();
        for (WarehouseImportData warehouseImportData : failList) {
            if (ObjectUtil.checkObjAllFieldsIsNull(warehouseImportData)) {
                failList.remove(failList);
            }
        }
        if (failList.size() > 0) {
            WarehouseImportData data = failList.get(0);
            String msg = "第" + (data.getRowNum() + 1) + "行的错误是：" + data.getErrorMsg();
            log.info(">>>:" + msg);
            throw new LogicException("第" + (data.getRowNum() + 1) + "行的错误是：" + data.getErrorMsg());
        }
        List<WarehouseImportData> list = result.getList();
        if (list == null || list.size() == 0) {
            throw new LogicException("上传文件数据为空，请查看");
        }
//        List<WarehouseParam> Wlist = new ArrayList<>();
        for (WarehouseImportData wid : list) {
            WarehouseParam param = new WarehouseParam();
            BeanUtils.copyProperties(wid, param);
//            Wlist.add(param);
            param.setAssetId(UUID.randomUUID().toString().replace("-", ""));
            insertWarehouse(param);
        }
        return true;
    }

    /**
     * 通过资产ID集合 查询 资产
     *
     * @param assetIds
     * @return
     */
    List<WarehouseResult> queryByAssetIds(List<String> assetIds) {
        if (assetIds == null || assetIds.size() == 0) {
            return new ArrayList<WarehouseResult>();
        }
        List<WarehouseResult> list = mapper.queryByAssetIds(assetIds);
        list.stream().forEach(e -> {
            List<AssetLog> assetLogs = assetLogMapper.queryLogByAssetId(e.getAssetId());
            e.setLogList(assetLogs);
            //
        });
        return list;
    }


    /**
     * 批量修改状态
     *
     * @param ids      资产ID
     * @param state    资产状态
     * @param userId   使用人Id
     * @param username 使用人姓名
     */
    public void updateAssetState(List<String> ids, String state, String userId, String username) {
        if (ids == null || ids.size() == 0) {
            return;
        }
        Warehouse warehouse = new Warehouse();
        warehouse.setState(state);
        warehouse.setHandlerUserId(userId);
        warehouse.setHandlerUser(username);

        // 通过使用人设置使用公司和使用部门===
        setCompanyAndDept(warehouse);
        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("assetId", ids);
        mapper.updateByExampleSelective(warehouse, example);
    }

    public void updateAsset(List<String> ids, Warehouse warehouse) {
        if (ids == null || ids.size() == 0) {
            return;
        }
        // 通过使用人设置使用公司和使用部门===
        setCompanyAndDept(warehouse);
        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("assetId", ids);
        mapper.updateByExampleSelective(warehouse, example);
    }

    /**
     * 通过 中间表关联ID 进行查询 资产信息
     *
     * @param tableName  查询的表名
     * @param columnName 查询的列名
     * @param otherId    列名对应得值
     * @return
     */
    public List<WarehouseResult> selectAssetRelation(String tableName, String columnName, String otherId) {
        List<WarehouseResult> list = mapper.selectAssetRelation(tableName, columnName, otherId);
        return list;
    }


    public Workbook printCard(List<String> assetIdList) throws IOException {
//        String filePath = FileManager.getReportPath("template","模板.xls");
//        File file = new File(filePath);
//        InputStream inputStream =  new FileInputStream(file);
//        POIFSFileSystem fs=new POIFSFileSystem(inputStream);
//        HSSFWorkbook wb=new HSSFWorkbook(fs);
        HSSFWorkbook wb = new HSSFWorkbook();
        List<WarehouseResult> warehouseResults = queryByAssetIds(assetIdList);
        for (int i = 0; i < warehouseResults.size(); i++) {
            WarehouseResult warehouse = warehouseResults.get(i);
            HSSFSheet sheet = wb.createSheet();
            // 设置打印页面
            ExcelStyle.printSetup(sheet);
            sheet.setColumnWidth(0, 3600);
            sheet.setColumnWidth(1, 272 * 18);
            sheet.setColumnWidth(2, 3600);
            sheet.setColumnWidth(3, 272 * 18);
            sheet.setColumnWidth(4, 3600);
            sheet.setColumnWidth(5, 272 * 20);

            wb.setSheetName(i, warehouse.getAssetCode());
            HSSFRow row_title = sheet.createRow(0);
            row_title.setHeight((short) (64 * 20));
            HSSFCell cell_title = row_title.createCell(0);

            cell_title.setCellValue("资产卡片");
            cell_title.setCellStyle(ExcelStyle.styleTitle(wb));
            row_title.setHeight((short) 690);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5)); // 合并单元格显示
            String[] cellName1 = {"资产编码", "资产名称", "资产分类"
                    , "规格型号", "SN号", "计量单位"
                    , "金额（元）", "使用公司", "使用部门"
                    , "使用人", "购入时间", "管理员"
                    , "所属公司", "区域", "存放地点"
                    , "使用期限（月）", "供应商", "资产来源"};
            String[] valueName1 = {warehouse.getAssetCode(), warehouse.getAssetName(), warehouse.getAssetClassName(),
                    warehouse.getSpecificationModel(), warehouse.getSnNumber(), warehouse.getUnitMeasurement(),
                    warehouse.getAmount(), warehouse.getUseCompanyName(), warehouse.getUseDeptName(),
                    warehouse.getHandlerUser(), warehouse.getPurchaseTime(), warehouse.getAdmin(),
                    warehouse.getCompanyName(), warehouse.getAreaName(), warehouse.getStorageLocation(),
                    warehouse.getServiceLife(), warehouse.getSupplierName(), warehouse.getSource()
            };
            AtomicInteger cellCount = new AtomicInteger();
            AtomicInteger valueCount = new AtomicInteger();
            for (int r = 1; r <= 6; r++) {
                HSSFRow row = sheet.createRow(r);
                for (int c = 0; c < 6; c++) {
                    HSSFCell cell = row.createCell(c);
                    if (c % 2 == 0) {
                        cell.setCellValue(cellName1[cellCount.getAndIncrement()]);
                        cell.setCellStyle(ExcelStyle.styleCellName(wb));

                        continue;
                    }
                    cell.setCellValue(valueName1[valueCount.getAndIncrement()]);
                    cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                }
            }
            HSSFRow row = sheet.createRow(7);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("备注");
            cell.setCellStyle(ExcelStyle.styleCellName(wb));
            cell = row.createCell(1);
            cell.setCellValue(warehouse.getRemark());
            cell.setCellStyle(ExcelStyle.styleCellValue(wb));
            // 备注 单元格样式
            CellRangeAddress remarkCell = new CellRangeAddress(7, 7, 1, 5);
            ExcelStyle.setBorder(wb, sheet, remarkCell);

            row = sheet.createRow(8);
            cell = row.createCell(0);
            cell.setCellValue("变更记录（最近5条记录）");
            cell.setCellStyle(ExcelStyle.styleCellValue(wb));
            // 添加 变更记录 单元格样式
            CellRangeAddress tipsCell = new CellRangeAddress(8, 8, 0, 5);
            ExcelStyle.setBorder(wb, sheet, tipsCell);


            row = sheet.createRow(9);
            String[] colName = {"处理日期", "处理人", "处理方式", "处理内容"};
            for (int c = 0; c < 4; c++) {
                cell = row.createCell(c);
                cell.setCellValue(colName[c]);
                cell.setCellStyle(ExcelStyle.styleCellName(wb));
            }
            // 添加 处理内容 单元格样式
            CellRangeAddress contentCell = new CellRangeAddress(9, 9, 3, 5);
            ExcelStyle.setBorder(wb, sheet, contentCell);

            AtomicInteger num = new AtomicInteger();
            List<AssetLog> logList = warehouse.getLogList();
            if (logList == null || logList.size() == 0) {
                continue;
            }
            for (int j = 10; j < (logList.size() > 5 ? 15 : 10 + logList.size()); j++) {
                AssetLog log = logList.get(num.getAndIncrement());
                row = sheet.createRow(j);
                cell = row.createCell(0);
                cell.setCellValue(log.getCreateTime());
                cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                cell = row.createCell(1);
                cell.setCellValue(log.getHandlerUser());
                cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                cell = row.createCell(2);
                cell.setCellValue(log.getLogType());
                cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                cell = row.createCell(3);
                cell.setCellStyle(ExcelStyle.styleCellValue(wb));
                cell.setCellValue(log.getHandlerContext());
                CellRangeAddress content = new CellRangeAddress(j, j, 3, 5);
                ExcelStyle.setBorder(wb, sheet, content);
            }
        }
        return wb;
    }

    public Workbook printWarehousing(List<String> assetIdList) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook();
        List<WarehouseResult> warehouseResults = queryByAssetIds(assetIdList);
        String title = "资产入库单";
        String sheetName = "资产入库";
        HSSFSheet sheet = wb.createSheet(sheetName);
        // 设置打印页面
        ExcelStyle.printSetup(sheet);
        sheet.setDefaultColumnWidth(10);
        sheet.setColumnWidth(0, 10 * 256);
        HSSFRow row_title = sheet.createRow(0);
        row_title.setHeight((short) (38 * 20));
        HSSFCell cell_title = row_title.createCell(1);
        cell_title.setCellValue(title);
        cell_title.setCellStyle(ExcelStyle.styleTitle(wb));
        row_title.setHeight((short) 690);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8)); // 合并单元格显示
        String[] cellName = {"资产条码", "资产类别",
                "资产名称", "规格型号",
                "金额", "购入时间",
                "所属公司", "供应商"};
        AtomicInteger cellCount = new AtomicInteger();
        HSSFRow row = sheet.createRow(1);
        for (int c = 1; c < 9; c++) {
            HSSFCell cell = row.createCell(c);
            cell.setCellValue(cellName[cellCount.getAndIncrement()]);
            cell.setCellStyle(ExcelStyle.styleCellName(wb));
        }
        AtomicInteger rowNum = new AtomicInteger(2);
        for (int i = 0; i < warehouseResults.size(); i++) {
            row = sheet.createRow(rowNum.getAndIncrement());
            WarehouseResult warehouse = warehouseResults.get(i);
            String[] valueName = {warehouse.getAssetCode(), warehouse.getAssetClassName(),
                    warehouse.getAssetName(), warehouse.getSpecificationModel(),
                    warehouse.getAmount(), warehouse.getPurchaseTime(),
                    warehouse.getCompanyName(), warehouse.getSupplierName()
            };
            AtomicInteger valueCount = new AtomicInteger();
            for (int c = 1; c < 9; c++) {
                HSSFCell cell = row.createCell(c);
                cell.setCellValue(valueName[valueCount.getAndIncrement()]);
                cell.setCellStyle(ExcelStyle.styleCellValue(wb));
            }
        }
//        采购人签字			使用人签字			管理员签字
        row = sheet.createRow(rowNum.getAndIncrement());
        HSSFCell cell = row.createCell(1);
        cell.setCellValue("采购人签字");
        cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 0));
        cell = row.createCell(4);
        cell.setCellValue("使用人签字");
        cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 0));
        cell = row.createCell(7);
        cell.setCellValue("管理员签字");
        cell.setCellStyle(ExcelStyle.styleNotBorder(wb, 0));
        return wb;
    }

    public List<WarehouseResult> queryByCompanyId(String companyId) {
        WarehousePagesParam param = new WarehousePagesParam();
        param.setCompanyId(companyId);
        return mapper.queryPages(param);
    }

    public List<Warehouse> queryByClassIdAndAreaId(String classId, String areaId) {
        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("area", areaId);
        criteria.andEqualTo("standardModel", classId);
        criteria.andEqualTo("state", "闲置");
        return mapper.selectByExample(example);
    }

    public String queryByAssetIdList(List<String> assetIdList) {
        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("assetId", assetIdList);
        List<Warehouse> warehouses = mapper.selectByExample(example);
        List<String> handlerUserIdList = warehouses.stream().map(warehouse -> warehouse.getHandlerUserId()).collect(Collectors.toList());
        Set<String> set = new HashSet<>(handlerUserIdList);
        if (set.size() == 1) {
            String handlerUserId = set.iterator().next();
            return handlerUserId;
        }
        return null;
    }

    /**
     * 修改分类时调用
     *
     * @param classPid
     * @param classId
     */
    public void updateAssetClassId(String classPid, String classId) {
        String userId = request.getHeader("userId");
        if (classPid == null || classId == null) {
            return;
        }
        // 查询子集是否是一个
        Example eclassExample = new Example(SetClass.class);
        Example.Criteria eclassCriteria = eclassExample.createCriteria();
        eclassCriteria.andEqualTo("pid", classPid);
        List<SetClass> setClasses = setClassMapper.selectByExample(eclassExample);
        if (setClasses != null && setClasses.size() > 1) {
            return;
        }
        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("assetClassId", classPid);
        List<Warehouse> warehouseList = mapper.selectByExample(example);

        for (Warehouse warehouse : warehouseList) {
            warehouse.setUpdateTime(DateTools.nowDate());
            warehouse.setUpdateUser(userId);
            warehouse.setAssetClassId(classId);
            mapper.updateByPrimaryKeySelective(warehouse);
        }
    }

    /**
     * 根据用户查询授权的资产
     *
     * @param userId
     * @param orgId
     * @return
     */
    public List<WarehouseResult> getAllByUserId(String userId, String orgId, String adminUser) {
        WarehousePagesParam param = new WarehousePagesParam();
        Boolean flag = true;
        // redis 查询用户权限： 如果是管理员为false 查询全部
        UserInfo user = assetReportMapper.selectUser(adminUser);
        if (user.getDataIsAll() == 1) {
            flag = false;
        }
        if ("2".equals(user.getType())) {
            param.setUserId(adminUser);
            flag = true;
        }
        if (flag) {
            // 查询公司
            String companyType = "1";
            List<String> companyList = mapper.queryRelationIdLists(adminUser, companyType);
            //资产类别
            String classType = "2";
            List<String> classList = mapper.queryRelationIdLists(adminUser, classType);
            // 查询区域
            String areaType = "3";
            List<String> areaList = mapper.queryRelationIdLists(adminUser, areaType);
            if ((companyList == null || companyList.size() == 0) || (classList == null || classList.size() == 0) || (areaList == null || areaList.size() == 0)) {
                return new ArrayList<WarehouseResult>();
            }
            param.setCompanyList(companyList);
            param.setClassList(classList);
            param.setAreaList(areaList);
        }
        param.setOrgId(orgId);
        param.setUserId(userId);
        return mapper.queryPages(param);
    }

    public void warehouseTotalNum(String orgId){
        Example example = new Example(Warehouse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orgId", orgId);
        criteria.andEqualTo("isDelete", 0);
        int count = mapper.selectCountByExample(example);
        UsageManagement ment = mapper.selUsage(orgId);
        if(ment.getType()!=3 && Integer.valueOf(ment.getNumber())<=count){
            throw new LogicException("已有资产数量不能超出购买资产数量");
        }
    }
}
